<?php
namespace app\api\controller;

use app\api\model\Member;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
class Index extends Controller
{
    //最新用户列表
    public function index(){
        $user = new \app\api\model\Member();
        $userfujin = $user->where('id',input('param.id'))->find();

        $list=$user->where('id','neq',input('param.id'))
            ->where('status','neq',1)
            ->limit(10)
            ->order('top','desc')
            ->order('id','desc')
            ->select();
        $data = [];
        foreach ($list as $k=>$vo){
            $data[$k]['id']=$vo['id'];
            $data[$k]['name'] = $vo['name'];
            $data[$k]['pic'] = $vo['pic'];
            if($vo['sex']==0){
                $sex='icon-nv.png';
            }elseif($vo['sex']==1){
                $sex='icon-nan.png';
            }
            $data[$k]['sex']=$sex;

            $data[$k]['job']=$vo->profile['job'];
            if($vo['status']==0){
                $status='等待认证';
            }elseif($vo['status']==2){
                $status='身份已认证';
            }
             if($vo['grade']==1){
                $grade = 'icon-huiyuan.png';
            }else{
                $grade = '';
            }

            $data[$k]['grade']=$grade;
            $data[$k]['status']=$status;
            $data[$k]['marrytime']=$vo->profile['marrytime'];
            $data[$k]['userinfo']=$vo->profile['age'].'岁•'.$vo->profile['shengao'].'cm•'.$vo->profile['city'].'•'.$vo->profile['xingzuo'];
            $latitude = $vo->nearby['latitude'];
            $longitude = $vo->nearby['longitude'];
            $data[$k]['juli'] = calcDistance($userfujin->nearby['latitude'],$userfujin->nearby['longitude'],$latitude,$longitude);
        }

 

        $lunbo = Db::table('lunbo')->where('status',1)->select();
        $lunbos=[];
        foreach($lunbo as &$v){
            $lunbos['lunbo'] = 'http://xqcs.langzhitu.com/uploads/'.$v['pic'];
            $lunbos['id'] = $v['id'];
            $lunboss[] = $lunbos;
        }
        
        
        return json(['data'=>$data,'lunbo'=>$lunboss]);
    }
    //附近用户列表
    public function nearby(){
        $newfujin = new \app\api\model\Nearby();
        $userfujin = $newfujin->where('member_id',input('param.id'))->find();

        $a = $newfujin->fujin($userfujin['latitude'],$userfujin['longitude'],100);
        if($a) {
            $uids = [];
            foreach ($a as $vo) {
                if ($vo['member_id']) {
                    if ($vo['member_id'] != input('param.id')){
                        $uids[] = $vo['member_id'];
                    }
                }
            }

            $member = new \app\api\model\Member();
            // 根据主键获取多个数据
            $list = Member::all($uids);
            $data = [];
            foreach ($list as $k=>$vo){
                $data[$k]['id'] = $vo['id'];
                $data[$k]['name'] = $vo['name'];
                $data[$k]['pic'] = $vo['pic'];
                if($vo['sex']==0){
                    $sex='icon-nv.png';
                }elseif($vo['sex']==1){
                    $sex='icon-nan.png';
                }
                $data[$k]['sex']=$sex;

                $data[$k]['job']=$vo->profile['job'];
                if($vo['status']==0){
                    $status='等待认证';
                }elseif($vo['status']==2){
                    $status='身份已认证';
                }
                $data[$k]['status']=$status;
                $data[$k]['marrytime']=$vo->profile['marrytime'];
                $data[$k]['userinfo']=$vo->profile['age'].'岁•'.$vo->profile['shengao'].'cm•'.$vo->profile['city'].'•'.$vo->profile['xingzuo'];
                $latitude = $vo->nearby['latitude'];
                $longitude = $vo->nearby['longitude'];
                $data[$k]['juli'] = calcDistance($userfujin['latitude'],$userfujin['longitude'],$latitude,$longitude);
            }
            return json(['data'=>$data]);
        }else{
            return false;
        }
    }
    //轮播接口
    public function lunbo(){
        $lunbo = new \app\api\model\Lunbo();
        $text_id = input('param.text_id');
        if($text_id){
            $data = $lunbo->where('id',$text_id)->find();
        }else{
            $data = $lunbo->where('status',1)
            ->select();
        }

        return json(['data'=>$data]);
    }

    //个人信息
    public function register(){
        $uid = input('param.uid');
        $member_info = new \app\api\model\MemberInfo();
        $data = [
            'uid' => $uid,
            'age' => input('param.age'),
            'height' => input('param.height'),
            'education' => input('param.education'),
            'job' => input('param.job'),
            'income' => input('param.income'),
            'address' => input('param.address'),
            'marrytime' =>input('param.marrytime')
        ];
        $member_info->save($data);
        return $member_info->id;
    }
    //择偶标准
    public function spouse(){
        $spouse = new \app\api\model\Spouse();

        $data = [
            'age' => input('param.age'),
            'heigth' => input('param.heigth'),
            'education' => input('param.education'),
            'income' => input('param.income')
        ];

        $spouse->save($data);
        return $spouse->id;
    }
    //短信接口
    public function smsapi()
    {
        $iphone = input('param.iphone');
        $uid = input('param.uid');
        $send = config('JUHE_SMS_CONFIG');
        if (isMobile($iphone)) {
            $code = rand(100000, 999999);
            $smsconf = array(
                'key' => $send['key'],
                'mobile' => $iphone,
                'tpl_id' => '49051',
                'tpl_value' => "#code#=".$code
            );
            $content = juhecurl($send['send_url'], $smsconf, 1);
            if ($content) {
                $result = json_decode($content, true);
                $error_code = $result['error_code'];
                if ($error_code == 0) {
                    $sms = new \app\api\model\Sms();
                    $issms = $sms->where('uid',$uid)->find();
                    if($issms){
                         $sms->where('uid',$uid)->update(['iphone'=>$iphone,'code'=>$code]);
                    }else {
                        $sms->data(['iphone' => $iphone, 'code' => $code, 'uid' => $uid, 'sid' => $result['result']['sid']]);
                        $sms->save();
                    }
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }else{
            $this->error('手机格式不正确');
        }
    }
    //验证接口
    public function verificsms(){
        $iphone = input('param.iphone');
        $sms = new \app\api\model\Sms();

        $a = $sms->where('iphone',$iphone)->find();
        if($a){
            if($a['code'] == input('param.code')){
                $user = new \app\api\model\Member();
                $data['id'] = $a['uid'];
                $data['phone'] = $iphone;
                $user->update($data);
                return true;
            }else{
                return false;//验证码不正确
            }
        }else{
            return false;//亲，请先获取验证吗
        }
    }

    public function search(){
        $user = new \app\api\model\MemberInfo();
        $userfujin = $user->where('member_id',input('param.id'))->find();

        if(input('param.mid')){
            $map['member_id'] = ['=', input('param.mid')];
        }else {
            $map = [];
            $map['member_id'] = ['<>', input('param.id')];
            if (input('param.age') != 'undefined') {
                $a = input('param.age');
                if($a = "46以上"){
                    $map['age'] = ['egt', 46];
                }else {
                    $b = explode('-', $a);
                    $map['age'] = ['between', [$b[0], $b[1]]];
                }

            }
            if (input('param.sex') != 'undefined') {
                $map['sex'] = input('param.sex');
            }
            if (input('param.education') != 'undefined') {
                $map['education'] = input('param.education');
            }
            if (input('param.shengao') != 'undefined') {
                $a = input('param.shengao');
                if($a = "190以上"){
                    $map['shengao'] = ['egt', 190];
                }else {
                    $b = explode('-', $a);
                    $map['shengao'] = ['between', [$b[0], $b[1]]];
                }

            }
        }

        //return $map;die;

        $list = $user->where($map)
            ->limit(10)
            ->order('id','desc')
            ->select();

        $data = [];
        foreach ($list as $k=>$vo){
            $data[$k]['member_id']=$vo['member_id'];
            $data[$k]['name'] = $vo->member['name'];
            $data[$k]['pic'] = $vo->member['pic'];
            if($vo['sex']==0){
                $sex='icon-nv.png';
            }elseif($vo['sex']==1){
                $sex='icon-nan.png';
            }
            $data[$k]['sex']=$sex;

            $data[$k]['job']=$vo['job'];
            if($vo->member['status']==0){
                $status='等待认证';
            }elseif($vo->member['status']==2){
                $status='身份已认证';
            }
            if($vo->member['grade']==1){
                $grade = 'icon-huiyuan.png';
            }else{
                $grade = '';
            }

            $data[$k]['grade']=$grade;
            $data[$k]['status']=$status;
            $data[$k]['marrytime']=$vo['marrytime'];
            $data[$k]['userinfo']=$vo['age'].'•'.$vo['shengao'].'•'.$vo['city'].'•'.$vo['xingzuo'];
            $latitude = $vo->member->nearby['latitude'];
            $longitude = $vo->member->nearby['longitude'];
            $data[$k]['juli'] = calcDistance($userfujin->member->nearby['latitude'],$userfujin->member->nearby['longitude'],$latitude,$longitude);
        }

        return json(['data'=>$data]);
    }

    // 登录获取openid
    public function getopenid()
    {
        $wd = $_GET['wd'];
        $jd = $_GET['jd'];
        $code = $_GET['code'];//小程序传来的code值
        $name = $_GET['name'];//小程序传来的用户昵称
        $headUrl = $_GET['headurl'];//小程序传来的用户头像地址
        $sex = $_GET['sex'];//小程序传来的用户性别  
        $appid='wx9f3e8e39f53daae1';
        $secret='0b39db60cf1eb056a101dced9ec6b27e';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code=' . $code . '&grant_type=authorization_code';
        $result = $this->curl_get($url);
        $openid = $result['openid'];

        $data['name'] = $name;
        $data['pic'] = $headUrl;
        $data['sex']= $sex;
        $data['openid']  = $openid;
        $data['create_time'] = date('y-m-d h:i:s',time());

        $user = Db::table('member')->where('openid',$openid)->find();
        if(!$user){
            Db::name('member')->insert($data);
            $id = Db::name('user')->getLastInsID();
            $users = Db::table('member')->where('id',$id)->find();
            $users['wd'] = $wd;
            $users['jd'] = $jd;
            Db::table('nearby')->insert(array('latitude'=>$wd,'longitude'=>$jd,'member_id'=>$id));
            Db::table('member_fujian')->insert(array('uid'=>$id));
            Db::table('member_info')->insert(array('member_id'=>$id,'sex'=>$data['sex']));
            Db::table('spouse')->insert(array('user_id'=>$id));
            Db::table('member_info_edit')->insert(array('uid'=>$id));
            return $users;
        }else{
            Db::table('member')->where('openid',$openid)->update(array('name'=>$name,'pic'=>$headUrl,'sex'=>$sex));
            Db::table('nearby')->where('member_id',$user['id'])->update(array('latitude'=>$wd,'longitude'=>$jd));
            grade_invalid($user['id']);
            $user['wd'] = $wd;
            $user['jd'] = $jd;
            return $user;
        }
    }
    public  function curl_get($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);// https请求不验证证书和hosts
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $res=json_decode(curl_exec($curl),true);
        curl_close($curl);
        return $res;
    }
    public function userinfo(){
        $id = $_GET['id'];
        $member = Db::table('member')->where('id',$id)->find();
        $member['phone'] = substr_replace($member['phone'],'****',3,4); 
        $userinfo = Db::table('member_info')->where('member_id',$id)->find();
        $pic = Db::table('member_fujian')->where('uid',$id)->where('type',3)->column('pic');
        foreach($pic as &$v){
            $v = ' http://xqcs.langzhitu.com/'.$v;
        }
        $spouse = Db::table('spouse')->where('user_id',$id)->find();
        
        $data['bgArr'] =  Db::table('member_fujian')->where('uid',$id)->where('type',1)->value('pic');
        $data['myinfo'] = $userinfo;
        $data['jieshaoArr'] = $userinfo['jianjie'];
        $data['imgArr'] = $pic;
        $data['renzhengArr'] = array('name'=>$userinfo['name'],'phone'=>$member['phone']);
        $data['ziliao'] = $userinfo;
        $data['biaozhun'] = $spouse;
        if($member['grade']==1){
           $data['vip'] = 'icon-huiyuan-01.png';
        }else{
            $data['vip'] = '';
        }
        return json($data);
    }
    public function jwd(){
        $id = $_GET['id'];
        $wd = $_GET['wd'];
        $jd = $_GET['jd'];
        Db::table('nearby')->where('member_id',$id)->update(array('latitude'=>$wd,'longitude'=>$jd));
    }
    public function imgdelete()
    {
        $delimg = request()->param('delimg');
        $newstr=strstr($delimg,'uploads');
        if(Db::table('member_fujian')->where('pic',$newstr)->delete()){
            unlink($_SERVER["DOCUMENT_ROOT"]."/".$newstr);
            return $newstr;
        }else{
            return '';
        }
    }
     public function updateuserinfo()
    {
        $id=request()->param('id');
        $data=request()->param('info/a');
        $address=$data['adress'];
        $b = $address[0];
        $a='';
        foreach($address as $v){
            $a.=$v.',';
        }
        $cc=rtrim($a,',');
       
        $arr['address']=$cc;
        $time=time();
        $arr['create_time']=date('Y-m-d H:i:s',$time);
        $arr['age']=$data['age'];
        $arr['jianjie']=$data['jieshao'];
        $arr['shengao']=$data['shengao'];
        $arr['income']=$data['shouru'];
        $arr['education']=$data['xueli'];
        $arr['xingzuo']=$data['xingzuo'];
        $arr['job']=$data['zhiye'];
        $arr['marrytime']=$data['marrytime'];
        $arr['city'] = $b;

        $spo['age']=$data['zoage'];
        $spo['heigth']=$data['zoshengao'];
        $spo['education']=$data['zoxueli'];
        $spo['income']=$data['zoshouru'];
        $spo['create_time']=date('Y-m-d H:i:s',$time);

        $datas['bage']=$data['bage'];
        $datas['bshengao']=$data['bshengao'];
        $datas['bxingzuo']=$data['bxingzuo'];
        $datas['bxueli']=$data['bxueli'];
        $datas['bzhiye']=$data['bzhiye'];
        $datas['bshouru']=$data['bshouru'];
        $datas['bmarrytime']=$data['bmarrytime'];
        $datas['bzoage']=$data['bzoage'];
        $datas['bzoshengao']=$data['bzoshengao'];
        $datas['bzoshouru']=$data['bzoshouru'];
        $datas['bzoxueli']=$data['bzoxueli'];
        $datas['region']=explode(',',$cc);
        $datas['jieshao']=$data['jieshao'];

         $erweima = Db::table('member_fujian')->field('id')->where('uid',$id)->where('type',2)->find();
        
        $edit=Db::table('member_info_edit')->where('uid',$id)->update($datas);
        $userinfo=Db::table('member_info')->where('member_id',$id)->update($arr);
        $spouse=Db::table('spouse')->where('user_id',$id)->update($spo);
        if($userinfo && $spouse && $edit){
            $data['adress']=explode(',',$cc);
            return json($erweima);
        }else{
            return json($erweima);
        }
    }

    public function member_info_edit()
    {
        $uid = request()->param('uid');
        $data = Db::table('member_info_edit')->where('uid',$uid)->find();
        $data['region']=explode(',',$data['region']);
        return json($data);

    }

}
